package com.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.ArrayList;
import java.util.List;

import com.entity.Product;
import com.form.Main1Form;

public class Main1Action extends Action {
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {

		Main1Form main1Form = (Main1Form) form;

		String select1 = main1Form.getSelect1();
		String select2 = main1Form.getSelect2();
		String select3 = main1Form.getSelect3();
		String keyword = main1Form.getKeyword();


	Connection conn = null;
	String url = "jdbc:mysql://localhost:3306/mysql";
	String user = "root";
	String password = "85428133";

	List<Product> productList = new ArrayList<Product>();
	try {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		conn = DriverManager.getConnection(url, user, password);
		Statement stmt = conn.createStatement();
		String sql = "select * from product where" +"("+"ProductKbnＡ ='"+select1+"'"+ "AND" + " ProductKbnＢ ='"+select2+"'"+ "AND"+" ProductKbnＣ ='"+select3+"'"+")" +" AND"+ " ProductName like '"+"%"+keyword+"%"+"'";

		ResultSet rs = stmt.executeQuery(sql);






        // 検索したデータを 配列 class にセット

//		List<Product>

        while(rs.next()) {
        	Product product = new Product();
        	product.setProductId(rs.getString("ProductId"));
        	product.setProductKbnＡ(rs.getString("ProductKbnＡ"));
        	product.setProductKbnＢ(rs.getString("ProductKbnＢ"));
        	product.setProductKbnＣ(rs.getString("ProductKbnＣ"));
        	product.setMaker(rs.getString("Maker"));
        	product.setProductName(rs.getString("ProductName"));

        	productList.add(product);
        }

		rs.close();
		stmt.close();
//		pstmt.close();
		conn.close();

//		throw new SQLException();

	} catch (ClassNotFoundException e) {
		System.out.println("Class not found");
	} catch (SQLException e) {
		System.out.println("Sql exception");
	} catch (Exception e) {
		System.out.println("exception");
	} finally {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			response.getWriter().println(e.getMessage());
		}
	}

	request.setAttribute("products", productList);
	return mapping.findForward("success");

}
}
